/**
 * 定位组件demo
 */
import React, {PureComponent} from 'react';
import {Map} from 'react-amap';
import {Input, Modal} from 'antd';

export default class MapSearch extends PureComponent {
  constructor(props) {
    super(props);
    this.toolBar = ['ToolBar'];
    this.mapInstance = null;
  }

  /***
   * 关闭地图
   */
  handleClose = () => {
    const {changeVisible} = this.props;
    changeVisible();
  };

  /**确定定位信息并返回给父组件*/
  handleOk = () => {
    const { changeVisible,getAddress } = this.props;
    const position = this.mapInstance.getAllOverlays('marker')[0].getPosition();
    let lng = position.getLng();
    let lat = position.getLat();
    let lnglat = [lng, lat];

    /**获得定位的地址*/
    window.AMap.plugin('AMap.Geocoder', () => {
      const geocoder = new window.AMap.Geocoder({});
      geocoder.getAddress(lnglat, function(status, result) {
        if (status === 'complete' && result.info === 'OK') {
          let address = result.regeocode.formattedAddress;
          getAddress(address,lng,lat);
        }
      });
    });
    changeVisible();
  };

  render() {
    const {visible} = this.props;
    const mapEvent = {
      created: (ins) => {
        window.AMap.plugin('AMap.Autocomplete', () => {
          const opts = { input: 'autoinput',
          };
          let auto= new window.AMap.Autocomplete(opts);
          auto.on('select', function(result) {
            ins.setCenter([result.poi.location.lng, result.poi.location.lat]);
            ins.getAllOverlays('marker')[0].setPosition([result.poi.location.lng, result.poi.location.lat]);
          });
        });
        this.mapInstance = ins;
        /**地图定位（内部在添加拖拽选址）*/
        window.AMap.plugin('AMap.Geolocation', () => {
          const geolocation = new window.AMap.Geolocation({});
          geolocation.getCityInfo((status, result) => {
            if (status === 'complete' && result.info === 'SUCCESS') {
              let lng = result.center[0];
              let lat = result.center[1];
              ins.setZoomAndCenter(14, [lng, lat]);
              //ins.getAllOverlays('marker')[0].setPosition([lng, lat]);


              /**
               * 拖拽选址
               */
              window.AMapUI.loadUI(['misc/PositionPicker'], PositionPicker => {
                //const center = this.mapInstance.getAllOverlays('marker')[0].getPosition();
                window.AMap.Map('container', {
                  zoom: 14,
                  resizeEnable: true,
                  center: [lng, lat]
                });
                let positionPicker = new PositionPicker({
                  mode: 'dragMarker', //设定为拖拽地图模式，可选'dragMap[拖拽地图]'、'dragMarker[拖拽点]'，默认为'dragMap'
                  map: this.mapInstance,
                  iconStyle:{//自定义外观
                    url:'//webapi.amap.com/ui/1.0/assets/position-picker.png',//图片地址
                    size:[28,28],  //要显示的点大小，将缩放图片
                    ancher:[24,40],//锚点的位置，即被size缩放之后，图片的什么位置作为选中的位置
                  }
                });
                positionPicker.on('success', positionResult => {
                  let locationMsg = {
                    lng: positionResult.position.lng, // 经度
                    lat: positionResult.position.lat, // 维度
                    address: positionResult.address, // 详细地址
                    nearestJunction: positionResult.nearestJunction, // 最近的路口
                    nearestRoad: positionResult.nearestRoad, // 最近的路
                    nearestPOI: positionResult.nearestPOI // 最近的POI
                  };
                  //console.log(locationMsg);
                  //将数据抛出
                  document.getElementById('autoinput').value = locationMsg.address;
                });
                positionPicker.on('fail', positionResult => {
                  // 海上或海外无法获得地址信息
                  alert('选址失败请稍后重试!');
                });
                positionPicker.start([lng, lat]);
              });
            }
          })
        });
      },
    };
    return (
      <Modal
        visible={visible}
        title="地图定位"
        okText="确定"
        onCancel={this.handleClose}
        onOk={this.handleOk}
        width="50%"
        destroyOnClose={true}
        maskClosable={false}
      >
        {
          visible &&
          <div style={{height: 400}}>
            <Input
              id={"autoinput"}
              placeholder="输入地名定位"
              style={{width: 400}}
            />
            <div style={{height: 360}}>
              <Map
               useAMapUI={true}
                version={'1.4.4'}
                plugins={this.toolBar}
                events={mapEvent}
                amapkey="788e08def03f95c670944fe2c78fa76f"
                >
                {/*<Marker draggable='true' draggable='true' title={'1111'}/>*/}
              </Map>
            </div>
          </div>
        }
      </Modal>
    );
  }
}

